/**
 * Created by congzhang on 17/11/8.
 */



var models = require("../dbs/models.js");
var exec = require('child_process').exec;
var fs = require('fs');

var path = require("path");


function writeLog(data) {

    var date = new Date().toLocaleString();

    var writeData = date + "\t" + data + "\n";

    fs.appendFileSync("./test.log", writeData);
}


function zhuanma() {
	models.Video.findOne({"status": 1}, function (err, data) {
		console.log(data);

		if(data){

			writeLog("获取任务,开始操作");

			const BASENAME = path.dirname(__dirname);

			var id = data._id;
			var videoPath = data.videoPath;

			models.Video.update({"_id": id}, {"$set": {"status": 2}}, function (err, res) {

				if (!err){

					var basename = path.basename(videoPath);
					var file_name = basename.split(".")[0] + ".mp4";

					var source_file_path = path.join(BASENAME + videoPath);             // 源文件地址
					var dest_file_path = path.join(BASENAME, "/video/", file_name);     // 目标文件地址

					var shell = "/usr/bin/ffmpeg -i " + source_file_path +" -strict -2 -s 1024*768 " + dest_file_path;

					console.log(shell);

					writeLog("开始转码");

					var last = exec(shell);

					last.stdout.on('data', function (data) {
						console.log('标准输出：' + data);
					});

					last.on('exit', function (code) {
						console.log('子进程已关闭，代码：' + code);

						models.Video.update({"_id": id}, {"$set": {"status": 3, "zhuanmaVideoPath": path.join("/video/", file_name)}}, function (err, res) {

							if (err) {
								console.log("Error:" + err);
							}
							else {
								writeLog("转码完成");
								console.log("Res:" + res);

								var shell = "sudo /usr/bin/rsync -vzrtopg --delete --progress " + dest_file_path + " upload_video@119.90.40.16::upload_video --password-file=/etc/.rsyncd.secrets";
								var last = exec(shell);
								last.stdout.on('data', function (data) {
									console.log('标准输出：' + data);

									models.Video.update({"_id": id}, {"$set": {"status": 4}}, function (err, res) {
										if(!err){
											console.log("更新成功");
											models.mongoose.disconnect();
										}
									})

								});
							}
						});

					});
				}

			});

		}else{

			writeLog("无任务");
			models.mongoose.disconnect();

		}
	});
}

var shell = "ps aux | grep ffmpeg | wc -l";

var last = exec(shell);

var flag = false;

last.stdout.on('data', function (data) {
	console.log("data --> ", data);
	if (data == 2){
		flag = true;
		console.log("可以操作")
	}
});

last.on('exit', function (code) {
	if (flag){
		writeLog("当前可以操作");
		zhuanma()
	} else{
		writeLog("当前不可以操作");
		models.mongoose.disconnect();
	}

});







